package com.peihua.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.peihua.domain.Result;
import com.peihua.domain.User;
import com.peihua.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userservice;

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        if (Objects.isNull(user)) {
            return Result.error("未输入信息");
        }
        LambdaQueryWrapper<User> getUser = new LambdaQueryWrapper<User>().eq(User::getPhone, user.getPhone());
        User userInfo = userservice.getOne(getUser);

        if (Objects.isNull(userInfo)) {
            return Result.error("没有该用户");
        }
        if (!Objects.equals(user.getPassword(), userInfo.getPassword())) {
            return Result.error("密码错误");
        }
        return Result.success("登陆成功");
    }

    @GetMapping("/phone/{phone}")
    public Result getUserByPhone(@PathVariable String phone) {
        LambdaQueryWrapper<User> Wrapper = new LambdaQueryWrapper<User>();
        Wrapper.eq(User::getPhone, phone);
        User luckinUser = userservice.getOne(Wrapper);
        return Result.success(luckinUser);
    }

    // 兼容保留：原有的 /user/user/{id}
    @GetMapping("/user/{id}")
    public Result getUserByIdCompat(@PathVariable Integer id) {
        LambdaQueryWrapper<User> Wrapper = new LambdaQueryWrapper<User>();
        Wrapper.eq(User::getId, id);
        User luckinUser = userservice.getOne(Wrapper);
        return Result.success(luckinUser);
    }

    // 新增规范路径：/user/{id}
    @GetMapping("/{id}")
    public Result getUserById(@PathVariable Integer id) {
        LambdaQueryWrapper<User> Wrapper = new LambdaQueryWrapper<User>();
        Wrapper.eq(User::getId, id);
        User luckinUser = userservice.getOne(Wrapper);
        return Result.success(luckinUser);
    }

    @PostMapping("/saveUser")
    public Result SaveUser(@RequestBody User user) {
        User getUserName = userservice.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        if (!Objects.isNull(getUserName)) {
            return Result.error(500L, "用户名已存在");
        }
        User getPhone = userservice.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, user.getPhone()));
        if (!Objects.isNull(getPhone)) {
            return Result.error(500L, "该手机号已使用");
        }
        userservice.save(user);
        return Result.success();
    }

    @PutMapping("/updateUser")
    public Result UpdateUser(@RequestBody User user) {
        userservice.updateById(user);
        return Result.success("修改成功");
    }
}
